package com.nodecollege.cloud.core.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 日志注解
 */
@Aspect
@Component
public class LogAop {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //切入点
    @Pointcut("@annotation(LogT)")
    public void log() {

    }

    @Around("log()")
    public Object aroundExec(ProceedingJoinPoint point) throws Throwable {

        //请求开始时间
        long start = System.currentTimeMillis();

        Object[] args = point.getArgs();

        //过滤request，和response
        List<Object> paramsList = new ArrayList<>();
        if (args != null) {
            for (Object ob : args) {
                //校验是否为baiwang包下的类
                if (checkClass(ob)) {
                    paramsList.add(ob);
                }
            }
        }

        //执行方法
        Object result = point.proceed();
        //请求耗时
        long time = System.currentTimeMillis() - start;

        //输出日志
        logger.info("method:{}; params:{}; response:{}; cost:[{}]", point.toShortString(), JSONObject.toJSONString(paramsList), JSONObject.toJSONString(result), time);

        return result;
    }

    public boolean checkClass(Object a) {
        /**
         * 循环遍历所有的元素，检测有没有这个名字
         */
        Class class1 = a.getClass();
        String name = class1.getName();
        if (name.contains("nodecollege") || name.contains("java.lang.String")) {
            return true;
        } else {
            return false;
        }
    }

}
